package com.bee.plus.ai;
import com.bee.plus.dto.MessageReq;
import com.bee.plus.dto.MessageResp;
import com.bee.plus.store.StoreManger;
import com.bee.plus.util.Conversation;
import com.bee.plus.util.ConversationThreadLocal;
import io.reactivex.Flowable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public abstract class MessagePrepare implements BaseAiService{


    @Autowired
    protected StoreManger storeManger;


    private static final  Logger logger= LoggerFactory.getLogger(MessagePrepare.class);


    @Override
    public final MessageResp chat(MessageReq messageReq) {
        // Call the before method before processing the message
        messageReq = preprocessMessage(messageReq);

        // Process the message and get the response
        MessageResp messageResp = processMessage(messageReq);

        // Call the after method after processing the response
        //postprocessResponse(messageResp);

        return messageResp;
    }

    @Override
    public final Flowable<MessageResp> chatStream(MessageReq messageReq) {
        // Call the before method before processing the message
        messageReq = preprocessMessage(messageReq);

        // Process the message and get the response
        Flowable<MessageResp> messageRespFlowable = processMessageStream(messageReq);

        return messageRespFlowable;
    }

    /**
     * 方法预处理
     * @param messageReq
     * @return
     */
    protected abstract MessageReq preprocessMessage(MessageReq messageReq);


    /**
     * 聊天的核心方法
     * @param messageReq
     * @return
     */
    protected abstract MessageResp processMessage(MessageReq messageReq);

    protected abstract Flowable<MessageResp> processMessageStream(MessageReq messageReq);


    /**
     * 方法后置的处理
     * @param messageResp
     */
    protected  void postprocessResponse(MessageResp messageResp,Long conversationId){
        if(messageResp==null){
            return;
        }
        if(StringUtils.isEmpty(messageResp.getContent())){
            return;
        }
        logger.info("postprocessResponse {}",messageResp.getContent());
        storeManger.getDb().storeChatInfo(messageResp,conversationId);
    }
}
